package cn.edu.hbsi.web.controller;

import cn.edu.hbsi.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Iterator;
import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController
{
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @GetMapping
    public List<User> getAllUser(){
        String sql = "select * from user";
        List<User> list = jdbcTemplate.query(sql,new BeanPropertyRowMapper<User>(User.class));
        Iterator var = list.iterator();
        while (var.hasNext()){
            User user = (User) var.next();
            System.out.println(user);
        }
        return list;
    }

    @GetMapping("/{id}")
    public User getUser(@PathVariable Integer id){
        String sql = "select * from user where id = ?";
        User user = (User) jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<User>(User.class),id);
        System.out.println(user);
        return user;
    }
}
